<template>
  <el-card>
    <el-form inline>
      <el-form-item>
        <el-input placeholder="用户名" v-model="username" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="getUserList"
          >查询</el-button
        >
        <el-button @click="reset">清空</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="showAddUser">添加</el-button>
    <el-button type="danger" disabled>批量删除</el-button>
    <el-table :data="userList" border class="mt-20">
      <el-table-column
        type="selection"
        width="60"
        align="center"
      ></el-table-column>
      <el-table-column
        type="index"
        label="序号"
        width="80"
        align="center"
      ></el-table-column>
      <el-table-column label="用户名" prop="username" width="200" />
      <el-table-column label="用户昵称" prop="nickName" width="200" />
      <el-table-column label="角色列表" prop="roleName" width="200" />
      <el-table-column label="创建时间" prop="gmtCreate" width="200" />
      <el-table-column label="更新时间" prop="gmtModified" width="200" />
      <el-table-column label="操作" width="200" fixed="right">
        <template v-slot="{ row }">
          <el-button
            type="info"
            :icon="User"
            size="small"
            @click="showAssignRole(row)"
          ></el-button>
          <el-button
            type="warning"
            :icon="Edit"
            size="small"
            @click="updateUser(row)"
          ></el-button>
          <el-button
            type="danger"
            :icon="Delete"
            size="small"
            @click="delUser(row.id)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout=" prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @size-change="getUserList"
      @current-change="getUserList"
      class="mt-20"
    />
    <el-dialog title="添加用户" v-model="isShowAddUserList">
      <el-form
        label-width="100px"
        ref="addUserFormRef"
        :model="addUserFormData"
        :rules="addUserFormRules"
      >
        <el-form-item label="用户名">
          <el-input placeholder="用户名" v-model="addUserFormData.username" />
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input placeholder="用户昵称" v-model="addUserFormData.nickName" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input placeholder="密码" v-model="addUserFormData.password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button type="primary" @click="addUser">保存</el-button>
          <el-button @click="isShowAddUserList = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="分配用户角色" v-model="assignRoleVisible">
      <el-form
        label-width="100"
        ref="assignRoleFormRef"
        :model="assignRoleFormData"
        :rules="assignRoleFormRules"
      >
        <el-form-item
          label="用户名"
          disabled
          v-model="assignRoleFormData.username"
        >
          <el-input />
        </el-form-item>
        <el-form-item label="角色列表" prop="roleId">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group
            v-model="assignRoleFormData.roleId"
            @change="handleCheckedRolesChange"
          >
            <el-checkbox
              v-for="role in allRolesList"
              :key="role.id"
              :label="role.id"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button type="primary" @click="assignRole">保存</el-button>
          <el-button @click="assignRoleVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "XUser",
};
</script>

<script lang="ts" setup>
import { Search, Edit, Delete, User } from "@element-plus/icons-vue";
import {
  getUserListApi,
  addUserApi,
  updateUserApi,
  removeUserApi,
  getUserRoleListApi,
  assignUserRoleListApi,
} from "@/api/acl/user";
import type {
  UserList,
  AddUserParams,
  UserItem,
  RolesList,
} from "@/api/acl/type/userType";
import { ref, onMounted, reactive } from "vue";
import type { CheckboxValueType } from "element-plus";
import { ElMessage } from "element-plus";
const assignRoleVisible = ref(false);
const checkAll = ref(false);
const isIndeterminate = ref(false);
const allRolesList = ref<RolesList>([]);
const assignRoleFormRef = ref();
const assignRoleFormData = reactive<{
  userId: string;
  roleId: string[];
  username: string;
}>({
  userId: "",
  roleId: [],
  username: "",
});
const showAssignRole = async (row: UserItem) => {
  assignRoleVisible.value = true;
  assignRoleFormData.userId = row.id;
  assignRoleFormData.username = row.username;
  assignRoleFormData.roleId = [];
  assignRoleFormRef.value?.clearValidate();
  const res = await getUserRoleListApi(row.id);
  console.log(res);

  allRolesList.value = res.allRolesList;
  assignRoleFormData.roleId = res.assignRoles.map((item) => item.id);
  handleCheckedRolesChange();
};
const assignRoleFormRules = reactive({
  roleId: [{ required: true, message: "请选择至少一个角色" }],
});
// 全选全不选
const handleCheckAllChange = (val: CheckboxValueType) => {
  if (val) {
    // 全选
    assignRoleFormData.roleId = allRolesList.value.map((item) => item.id);
  } else {
    // 全不选
    assignRoleFormData.roleId = [];
  }
  isIndeterminate.value = false;
};
const handleCheckedRolesChange = () => {
  if (assignRoleFormData.roleId.length === 0) {
    // 全不选
    isIndeterminate.value = false;
    checkAll.value = false;
  } else if (assignRoleFormData.roleId.length === allRolesList.value.length) {
    // 全选
    isIndeterminate.value = false;
    checkAll.value = true;
  } else {
    isIndeterminate.value = true;
  }
};
const assignRole = async () => {
  await assignRoleFormRef.value.validate();
  await assignUserRoleListApi(
    assignRoleFormData.userId,
    assignRoleFormData.roleId
  );
  ElMessage.success("分配角色成功");
  getUserList();
  assignRoleVisible.value = false;
};
// 清空
const reset = () => {
  username.value = "";
  getUserList();
};
/****************删除用户***************** */
const delUser = async (id: string) => {
  await removeUserApi(id);
  getUserList();
};
/**********************修改用户*************************** */
const updateUser = (row: UserItem) => {
  isShowAddUserList.value = true;
  addUserFormData.id = row.id;
  addUserFormData.username = row.username;
  addUserFormData.nickName = row.nickName;
  addUserFormData.password = "";
  addUserFormRef.value?.clearValidate();
};
/******************添加用户********************* */
const isShowAddUserList = ref(false);
const addUserFormRef = ref();
const addUserFormData = reactive<AddUserParams>({
  id: undefined,
  nickName: "",
  password: "",
  username: "",
});
const showAddUser = () => {
  isShowAddUserList.value = true;
  addUserFormData.username = "";
  addUserFormData.nickName = "";
  addUserFormData.password = "";
};
// 校验规则
const addUserFormRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  nickName: [{ required: true, message: "请输入用户昵称", trigger: "blur" }],
  password: [{ required: true, message: "请输入用户密码", trigger: "blur" }],
});
const addUser = async () => {
  await addUserFormRef.value.validate();
  const id = addUserFormData.id;
  if (id) {
    await updateUserApi({ ...addUserFormData, id });
  } else {
    await addUserApi(addUserFormData);
  }
  getUserList();
  isShowAddUserList.value = false;
};
/********************获取管理用户列表 ************************/
const currentPage = ref(1);
const pageSize = ref(5);
const username = ref("");
const total = ref(100);
const userList = ref<UserList>([]);
onMounted(() => {
  getUserList();
});
// 获取管理用户列表
const getUserList = async () => {
  const res = await getUserListApi({
    page: currentPage.value,
    limit: pageSize.value,
    username: username.value,
  });
  total.value = res.total;
  userList.value = res.items;
};
</script>

<style scoped></style>
